<template>
    <div class="product-detail">
        <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8">
                <!-- 商品图片 -->
                <el-carousel :interval="4000" type="card" height="400px">
                    <el-carousel-item v-for="(image, index) in product.images" :key="index">
                        <el-image :src="image" fit="cover" style="width: 100%; height: 100%"></el-image>
                    </el-carousel-item>
                </el-carousel>
            </el-col>
            <el-col :xs="24" :sm="12" :md="16">
                <div class="product-info">
                    <!-- 商品标题和价格 -->
                    <h1 class="product-title">{{ product.name }}</h1>
                    <div class="product-price">¥{{ product.price }}</div>
                    
                    <!-- 商品元数据 -->
                    <div class="product-meta">
                        <div class="meta-item">
                            <el-icon><Location /></el-icon>
                            <span>{{ product.location }}</span>
                        </div>
                        <div class="meta-item">
                            <el-icon><View /></el-icon>
                            <span>{{ product.views }} 浏览</span>
                        </div>
                        <div class="meta-item">
                            <el-icon><Timer /></el-icon>
                            <span>{{ product.publishTime }} 发布</span>
                        </div>
                    </div>
                    
                    <!-- 商品描述 -->
                    <div class="product-description">
                        <h3>商品详情</h3>
                        <p>{{ product.description }}</p>
                    </div>
                    
                    <!-- 卖家信息 -->
                    <div class="seller-info">
                        <h3>卖家信息</h3>
                        <div class="seller-profile">
                            <el-avatar :size="50" :src="product.seller.avatar"></el-avatar>
                            <div class="seller-details">
                                <div class="seller-name">{{ product.seller.name }}</div>
                                <div class="seller-rating">
                                    <el-rate v-model="product.seller.rating" disabled />
                                    <span>({{ product.seller.ratingCount }}条评价)</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="action-buttons">
                        <el-button type="primary" size="large" @click="handleBuyNow" :disabled="!isAvailable">
                            <el-icon>
                                <Shopping />
                            </el-icon>
                            立即购买
                        </el-button>
                        <el-button type="success" size="large" @click="handleContact">
                            <el-icon>
                                <ChatDotRound />
                            </el-icon>
                            联系卖家
                        </el-button>
                        <el-button size="large" @click="handleCollect">
                            <el-icon>
                                <Star />
                            </el-icon>
                            收藏
                        </el-button>
                    </div>
                    
                    <!-- 下单确认对话框 -->
                    <el-dialog
                        v-model="orderDialogVisible"
                        title="确认购买"
                        width="30%"
                    >
                        <div class="order-confirm">
                            <div class="product-summary">
                                <img :src="product.images[0]" alt="商品图片" class="summary-image" />
                                <div class="summary-info">
                                    <h3>{{ product.name }}</h3>
                                    <p class="price">¥{{ product.price }}</p>
                                </div>
                            </div>
                            
                            <el-form :model="orderForm" label-width="80px">
                                <el-form-item label="支付方式">
                                    <el-radio-group v-model="orderForm.paymentMethod">
                                        <el-radio label="线下支付">线下支付</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="备注">
                                    <el-input v-model="orderForm.remark" type="textarea" rows="3" placeholder="选填，请输入备注信息" maxlength="200" show-word-limit></el-input>
                                </el-form-item>
                            </el-form>
                            
                            <div class="order-summary">
                                <div class="summary-item">
                                    <span>商品金额：</span>
                                    <span class="price">¥{{ product.price }}</span>
                                </div>
                            </div>
                        </div>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="orderDialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="confirmOrder" :loading="orderLoading">
                                    确认购买
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                </div>
            </el-col>
        </el-row>

        <!-- 相关推荐 -->
        <div class="related-products">
            <h2>相关推荐</h2>
            <el-row :gutter="20">
                <el-col :span="6" v-for="item in relatedProducts" :key="item.id">
                    <el-card class="product-card" @click="goToProduct(item.id)">
                        <el-image :src="item.image" fit="cover" />
                        <div class="product-info">
                            <h3>{{ item.name }}</h3>
                            <div class="product-price">¥{{ item.price }}</div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Location, View, Timer, ChatDotRound, Star, Shopping } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'
import { useOrderStore } from '@/stores/order'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const orderStore = useOrderStore()

const product = ref({
    id: 1,
    name: 'iPhone 13 Pro Max',
    price: 6999,
    images: [
        'https://via.placeholder.com/800x600/409EFF/FFFFFF?text=iPhone+13+Pro+Max+1',
        'https://via.placeholder.com/800x600/67C23A/FFFFFF?text=iPhone+13+Pro+Max+2',
        'https://via.placeholder.com/800x600/E6A23C/FFFFFF?text=iPhone+13+Pro+Max+3'
    ],
    location: '北京大学',
    views: 1000,
    publishTime: '2024-04-01',
    description: 'iPhone 13 Pro Max 256GB 石墨色，国行在保，无拆无修，成色99新，全套包装配件齐全。',
    seller: {
        name: '张三',
        avatar: 'https://via.placeholder.com/100/409EFF/FFFFFF?text=张三',
        rating: 4.5,
        ratingCount: 120
    }
})

const relatedProducts = ref([
    {
        id: 2,
        name: 'iPhone 13 Pro',
        price: 5999,
        image: 'https://via.placeholder.com/300x200/409EFF/FFFFFF?text=iPhone+13+Pro'
    },
    {
        id: 3,
        name: 'iPhone 12 Pro Max',
        price: 4999,
        image: 'https://via.placeholder.com/300x200/67C23A/FFFFFF?text=iPhone+12+Pro+Max'
    },
    {
        id: 4,
        name: 'iPhone 12 Pro',
        price: 3999,
        image: 'https://via.placeholder.com/300x200/E6A23C/FFFFFF?text=iPhone+12+Pro'
    },
    {
        id: 5,
        name: 'iPhone 11 Pro Max',
        price: 2999,
        image: 'https://via.placeholder.com/300x200/F56C6C/FFFFFF?text=iPhone+11+Pro+Max'
    }
])

// 订单相关
const orderDialogVisible = ref(false)
const orderLoading = ref(false)
const orderForm = ref({
    paymentMethod: '线下支付',
    remark: ''
})

// 检查商品是否可购买
const isAvailable = computed(() => {
    // 这里可以根据实际情况判断商品是否可购买
    // 例如：商品状态为在售，没有被下架等
    return true
})

// 获取卖家信息
const fetchSellerInfo = async (sellerId) => {
    try {
        const response = await axios.get('/user/info', {
            params: {
                userId: sellerId
            }
        })
        if (response.data.code === 200 && response.data.data) {
            // 更新卖家信息
            product.value.seller = {
                ...product.value.seller,
                ...response.data.data,
                name: response.data.data.userName || product.value.seller.name,
                avatar: response.data.data.avatar || product.value.seller.avatar,
                rating: response.data.data.rating || product.value.seller.rating,
                ratingCount: response.data.data.ratingCount || product.value.seller.ratingCount
            }
        }
    } catch (error) {
        console.error('获取卖家信息失败:', error)
    }
}

onMounted(() => {
    // TODO: 根据路由参数获取商品详情
    const productId = route.params.id
    console.log('Loading product:', productId)
    
    // 获取商品详情后，请求卖家信息
    if (product.value.seller && product.value.seller.id) {
        fetchSellerInfo(product.value.seller.id)
    }
})

// 点击立即购买
const handleBuyNow = () => {
    if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
    }
    
    orderDialogVisible.value = true
}

// 确认下单
const confirmOrder = async () => {
    orderLoading.value = true
    
    try {
        const orderData = {
            productId: product.value.id,
            paymentMethod: orderForm.value.paymentMethod,
            remark: orderForm.value.remark
        }
        
        const result = await orderStore.createOrder(orderData)
        
        if (result) {
            ElMessage.success('下单成功')
            orderDialogVisible.value = false
            
            // 跳转到订单详情页
            router.push(`/order/${result.id}`)
        } else {
            ElMessage.error('下单失败，请重试')
        }
    } catch (error) {
        console.error('下单失败:', error)
        ElMessage.error('下单失败，请重试')
    } finally {
        orderLoading.value = false
    }
}

const handleContact = () => {
    // TODO: 实现联系卖家的功能
    console.log('Contact seller')
}

const handleCollect = () => {
    // TODO: 实现收藏功能
    console.log('Collect product')
}

const goToProduct = (id) => {
    router.push(`/product/${id}`)
}
</script>

<style scoped>
.product-detail {
    padding: 20px;
}

.product-info {
    padding: 20px;
}

.product-title {
    font-size: 24px;
    margin-bottom: 10px;
}

.product-price {
    font-size: 28px;
    color: #f56c6c;
    font-weight: bold;
    margin-bottom: 20px;
}

.product-meta {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    color: #909399;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 5px;
}

.product-description {
    margin: 20px 0;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 8px;
}

.seller-info {
    margin: 20px 0;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 8px;
}

.seller-profile {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-top: 10px;
}

.seller-details {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.seller-name {
    font-size: 16px;
    font-weight: bold;
}

.seller-rating {
    display: flex;
    align-items: center;
    gap: 10px;
}

.action-buttons {
    display: flex;
    gap: 20px;
    margin-top: 30px;
}

.related-products {
    margin-top: 40px;
}

.related-products h2 {
    margin-bottom: 20px;
}

.product-card {
    cursor: pointer;
    transition: all 0.3s;
}

.product-card:hover {
    transform: translateY(-5px);
}

.product-card .product-info {
    padding: 10px;
}

.product-card .product-price {
    font-size: 18px;
    margin: 10px 0;
}

/* 订单对话框样式 */
.order-confirm {
    padding: 10px;
}

.product-summary {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.summary-image {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    margin-right: 16px;
}

.summary-info h3 {
    margin: 0 0 8px;
    font-size: 16px;
    color: #303133;
}

.price {
    color: #F56C6C;
    font-size: 16px;
    font-weight: 600;
}

.order-summary {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.summary-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}
</style>